<template>
  <ContentWrap>
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">样品信息</span>
          <div class="right-button">
            <!-- <el-button type="primary" @click="handleSubmit">送检</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button> -->
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="mt-20px"
      >
        <!-- 项目信息 -->
        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">基本信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="样品名称" prop="projectName">
                <el-input disabled v-model="formData.sampleName" placeholder="请输入样品名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="样品编号" prop="sampleNum">
                <el-input disabled v-model="formData.sampleNum" placeholder="请输入样品编号" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="盲样编号" prop="blindSampleNum">
                <el-input disabled v-model="formData.blindSampleNum" placeholder="请输入样品编号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格型号" prop="model">
                <el-input disabled v-model="formData.model" placeholder="请输入规格型号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="执行标准" prop="executiveStandard">
                <el-input disabled v-model="formData.executiveStandard" placeholder="请输入执行标准" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="受检单位" prop="receiveCheckCompany">
                <el-input disabled v-model="formData.receiveCheckCompany" placeholder="请输入受检单位" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="委托单位" prop="entrustCompany">
                <el-input disabled v-model="formData.entrustCompany" placeholder="请输入受检单位" />
              </el-form-item>
            </el-col>
            
            <el-col :span="8">
              <el-form-item label="生产单位" prop="productionCompany">
                <el-input disabled v-model="formData.productionCompany" placeholder="请输入生产单位" />
              </el-form-item>
            </el-col>

          </el-row>

     
        </el-card>

        <!-- 基本信息 -->
        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">抽样信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="抽样地点" prop="samplingSite">
                <el-input disabled v-model="formData.samplingSite" placeholder="请输入抽样地点" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="抽样日期" prop="samplingDate">
                <el-date-picker
                style="width: 100%;"
                disabled
                  v-model="formData.samplingDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="样品批（罐）号" prop="sampleBatchNum">
                <el-input disabled v-model="formData.sampleBatchNum" placeholder="请输入样品批（罐）号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="生产日期" prop="productionDate">
                <el-date-picker
                style="width: 100%;"
                disabled
                  v-model="formData.productionDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="产品包装" prop="productPackaging">
                <el-input disabled v-model="formData.productPackaging" placeholder="请输入产品包装" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="存放条件" prop="storeCondition">
                <el-input disabled v-model="formData.storeCondition" placeholder="请输入产品包装" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="物资编码" prop="sampleCode">
                <el-input disabled v-model="formData.sampleCode" placeholder="请输入物资编码" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="抽样基数" prop="samplingCardinalNum">
                <el-input disabled v-model="formData.samplingCardinalNum" placeholder="请输入抽样基数" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="抽取样品量" prop="samplingQuantity">
                <el-input disabled v-model="formData.samplingQuantity" placeholder="请输入抽样基数" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="封样形式" prop="sealedSampleMethod">
                <el-input disabled v-model="formData.sealedSampleMethod" placeholder="请输入封样形式" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="运送方式" prop="deliveryType">
                <el-input disabled v-model="formData.deliveryType" placeholder="请输入运送方式" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="陪同抽样人" prop="accompanySamplingPerson">
                <el-input disabled v-model="formData.accompanySamplingPerson" placeholder="请输入陪同抽样人" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="抽样人员" prop="samplingPerson">
                <el-input disabled v-model="formData.samplingPerson" placeholder="请输入抽样人员" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="受检单位人员" prop="receiveCheckCompanyPerson">
                <el-input disabled v-model="formData.receiveCheckCompanyPerson" placeholder="受检单位人员" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
            <el-form-item label="抽样方式" prop="standardType">
                <el-select disabled v-model="formData.standardType" placeholder="请选择抽样方式">
                  <el-option label="委托方自行抽样" :value="0" />
                  <el-option label="机构自抽自检" :value="1" />
                  <el-option label="第三方抽样" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>


            <el-col :span="8">
              <el-form-item label="承检单位" prop="orgName">
                <el-input disabled v-model="formData.receiveCheckCompanyPerson" placeholder="受检承检单位" />
              </el-form-item>
            </el-col>


            <el-col :span="8">
              <el-form-item label="检测开始时间" prop="checkStartTime">
                <el-input disabled v-model="formData.checkStartTime" placeholder="受检单位人员" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="检测结束时间" prop="checkStartTime">
                <el-input disabled v-model="formData.checkStartTime" placeholder="检测结束时间" />
              </el-form-item>
            </el-col>


            <el-col :span="8">
              <el-form-item label="检验人员" prop="checkStartTime">
                <el-input disabled v-model="formData.checkStartTime" placeholder="检验人员" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="审批人" prop="approvalByName">
                <el-input disabled v-model="formData.approvalByName" placeholder="审批人" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="报告编号" prop="reportNum">
                <el-input disabled v-model="formData.reportNum" placeholder="报告编号" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="报告日期" prop="reportDate">
                <el-input disabled v-model="formData.reportDate" placeholder="报告日期" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="检验状态" prop="checkStartTime">
                <el-input disabled v-model="formData.checkStateString" placeholder="检验状态" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="执行标准" prop="executiveStandard">
                <el-input v-model="formData.executiveStandard" placeholder="请输入执行标准" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="标准类型" prop="standardType">
                <el-select v-model="formData.standardType" placeholder="请选择标准类型">
                  <el-option label="手填" value="0" />
                  <el-option label="选择" value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="盲样编号" prop="blindSampleNum">
                <el-input v-model="formData.blindSampleNum" placeholder="请输入盲样编号" />
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-card>


        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">退样说明</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="退样方式" prop="returnSampleType">
                <el-radio-group disabled v-model="formData.returnSampleType">
                  <el-radio :label="0">不退</el-radio>
                  <el-radio :label="1">退</el-radio>
                  <el-radio :label="2">部分退</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20" v-if="formData.returnSampleType != 0">
            <el-col :span="8">
              <el-form-item label="退样收货人" prop="returnSampleReceiveBy">
                <el-input disabled v-model="formData.returnSampleReceiveBy" placeholder="请输入退样收货人" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="退样收货地址" prop="returnSampleReceiveAddress">
                <el-input
                disabled
                  v-model="formData.returnSampleReceiveAddress"
                  placeholder="请输入退样收货地址"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收货联系方式" prop="returnSampleReceivePhone">
                <el-input
                disabled
                  v-model="formData.returnSampleReceivePhone"
                  placeholder="请输入收货联系方式"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">抽样单签字版扫描件、样品照片</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="附件上传" prop="attachments">
                <el-upload
                  disabled
                  action="#"
                :on-preview="handlePreview"
                  :auto-upload="false"
                   :on-change="handleFileChange"
                    :file-list="fileList"
                >
                  <el-button disabled type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">检验结果</div>
          </template>

          <el-form v-model="JyjgForm" inline  label-width="120px">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="检验结论">
              <el-input
             style="width: 330px"
              disabled
                v-model="JyjgForm.a"
                placeholder="检验结论"
              />
            </el-form-item>
              </el-col>


              <el-col :span="8">

                <el-form-item label="退回原因">
              <el-input
              style="width: 330px"
              disabled
                v-model="JyjgForm.b"
                placeholder="退回原因"
              />
            </el-form-item>
                </el-col>
            </el-row>
          



          </el-form>

          <el-table v-loading="loading" :data="checkResultList" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column label="序号" type="index" align="center"  />
      <el-table-column label="检测项目" align="center" prop="checkProject" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="设计要求" align="center" prop="designRequire" />
      <el-table-column label="检验结果" align="center" prop="checkResult" />
      <el-table-column label="单位判定" align="center" prop="singleDecision" />
      <el-table-column label="执行标准" align="center" prop="standardType" />
      <el-table-column label="备注" align="center" prop="remark" />

    </el-table>
</el-card>

<el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">检验报告</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="附件上传" prop="attachments">
                <el-upload
                disabled
                  action="#"
                 :on-preview="handlePreview"
                  :auto-upload="false"
                   :on-change="handleFileChange1"
                    :file-list="fileList1"
                >
                  <el-button disabled type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 检验信息 -->
        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">项目信息</div>
          </template>
          <el-row :gutter="20">
         
              <el-col :span="8">
              <el-form-item label="项目名称" prop="projectName">
                <el-input disabled  style="width:330px" v-model="formData.projectManage.name" placeholder="请输入项目名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
            <el-form-item  label="项目起始日期" prop="startTime">
              <el-input disabled style="width:330px"  v-model="formData.projectManage.startTime" placeholder="请输入项目名称" />
                <!-- <el-date-picker
                  v-model="formData.projectStartDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                /> -->
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目截止日期" prop="endTime">
                <el-input  disabled style="width:330px" v-model="formData.projectManage.endTime" placeholder="请输入项目截止日期" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="甲方单位" prop="fistParty">
                <el-input disabled style="width:330px" v-model="formData.projectManage.firstpartyName" placeholder="请输入甲方单位" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item  label="合同金额(万元)" prop="contractAmount">
                <el-input disabled style="width:330px" v-model="formData.projectManage.contractAmount" placeholder="请输入合同金额（万元）" />
              </el-form-item>
            </el-col>

            
          <el-col :span="8">
              <el-form-item label="合同编号" prop="contractNum">
                <el-input disabled style="width:330px" v-model="formData.projectManage.contractNum" placeholder="请输入合同编号" />
              </el-form-item>
            </el-col>

          </el-row>

            <el-col :span="8">
              <el-form-item label="项目管理员" prop="projectManager">
                <el-input style="width:330px" disabled v-model="formData.projectManage.projectManager" placeholder="请输入项目管理员" />
              </el-form-item>
            </el-col>


        </el-card>


        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">状态变更历史</div>
          </template>

        <div style="max-height: 200px; overflow: auto;">
          <el-table v-loading="loading" :data="sampleChangeList" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="状态" align="center" prop="typeString" />
      <el-table-column label="日期" align="center" prop="createTime" />
      <el-table-column label="间隔天数" align="center" prop="intervalDays" />
      <el-table-column label="操作人" align="center" prop="name" />


    </el-table>
        </div>
</el-card>

        <!-- 检验结果 -->

        <!-- 检验要求 -->

      </el-form>
    </el-card>
  </ContentWrap>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { SampleInformationApi } from '@/api/qis/sampleinformation'
import { useMessage } from '@/hooks/web/useMessage'
import { Plus } from '@element-plus/icons-vue'

const router = useRouter()
const message = useMessage()
const formRef = ref()

const fileList = ref([])  
const fileList1 = ref([])
let formData = reactive({
  // 项目信息
  projectName: '',
  projectStartDate: '',
  projectEndDate: '',
  partyA: '',
  contractAmount: undefined,
  contractNum: '',
  projectManager: '',
  projectManage:{
    name:'',
    startTime:'',
    endTime:'',
    contractAmount: '',
			firstpartyId: '',
			contractNum: "",
			projectManager: "",
			orgIds: "",
			thirdpartyId: '',
			firstpartyName: "",
			orgNames: "",
  },

  // 基本信息
  sampleName: '',
  sampleNum: '',
  model: '',
  executiveStandard: '',
  standardType: '',
  blindSampleNum: '',

  // 单位信息
  entrustCompany: '',
  productionCompany: '',
  receiveCheckCompany: '',

  // 抽样信息
  samplingSite: '',
  samplingDate: '',
  sampleBatchNum: '',
  productionDate: '',
  productPackaging: '',
  storeCondition: '',
  sampleCode: '',
  samplingCardinalNum: '',
  samplingQuantity: '',
  sealedSampleMethod: '',
  deliveryType: '',
  samplingPerson: '',
  accompanySamplingPerson: '',
  receiveCheckCompanyPerson: '',
  samplingType: '',

  // 退样信息
  returnSampleType: '0',
  returnSampleReceiver: '',
  returnSampleAddress: '',
  returnSamplePhone: '',

  // 检验要求
  checkType: '',
  checkTimeLimit: '',
  inspectionOrg: '',
  resultRequireType: '1',
  targetRequireType: '1',
  checkAccordingTo: '',
  remark: '',
  attachments: []
})

const JyjgForm = ref({})  // 检验结果表单

const rules = {
  projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  sampleName: [{ required: true, message: '请输入样品名称', trigger: 'blur' }],
  sampleNum: [{ required: true, message: '请输入样品编号', trigger: 'blur' }],
  samplingDate: [{ required: true, message: '请选择抽样日期', trigger: 'change' }],
  entrustCompany: [{ required: true, message: '请输入委托单位', trigger: 'blur' }],
  productionCompany: [{ required: true, message: '请输入生产单位', trigger: 'blur' }],
  samplingSite: [{ required: true, message: '请输入抽样地点', trigger: 'blur' }],
  checkType: [{ required: true, message: '请选择检验类型', trigger: 'change' }]
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await SampleInformationApi.createSampleInformation(formData)
        message.success('送检成功')
        goBack()
      } catch (error) {
        message.error('送检失败')
      }
    }
  })
}

const handleSave = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await SampleInformationApi.createSampleInformation(formData)
        message.success('保存成功')
        goBack()
      } catch (error) {
        message.error('保存失败')
      }
    }
  })
}

const imgUrl = ref([])

const handleFileChange = async (file: any,fileList) => {
  console.log(fileList,'fileList')
  // const   current = fileList.map(item => item.url);
  // formData.signAndSampleUrl = current.join(',')
  // console.log(formData.value.signAndSampleUrl,'formData.value.signAndSampleUrl')

  const fileDataFile = new FormData()
fileDataFile.append('file',file.raw)

//   fileList2.value = fileList1;
//   const formDataFile = new FormData();
//   fileList2.value.forEach((file)=>{
//     formDataFile.append('file',file)

//   })

const res =  await  SampleInformationApi.uploadFileApi(fileDataFile)
imgUrl.value = res.data
formData.signAndSampleUrl = res
message.success('上传成功')
}

const handleFileChange1 = async (file: any,fileList) => {
  console.log(fileList,'fileList')
  // const   current = fileList.map(item => item.url);
  // formData.signAndSampleUrl = current.join(',')
  // console.log(formData.value.signAndSampleUrl,'formData.value.signAndSampleUrl')

  const fileDataFile = new FormData()
fileDataFile.append('file',file.raw)

//   fileList2.value = fileList1;
//   const formDataFile = new FormData();
//   fileList2.value.forEach((file)=>{
//     formDataFile.append('file',file)

//   })

const res =  await  SampleInformationApi.uploadFileApi(fileDataFile)
imgUrl.value = res.data
formData.signAndSampleUrl = res
message.success('上传成功')
}
const sampleChangeList = ref([])
const route = useRoute()
const checkResultList = ref([])
const getDetails = async ()=>{
  const res = await SampleInformationApi.getSampleInformation(route.query.id)
  console.log(res,'RES')
  checkResultList.value = res.checkResultList
  sampleChangeList.value = res.sampleChangeList
  formData = Object.assign(formData,res)
  let url = res.signAndSampleUrl
  let url1 = res.checkReportUrl
  console.log(url1,'url1')
  fileList.value.push(
      {
        uid: new Date().getTime(), // 生成唯一的 uid
      name: url.split('/').pop(), // 从 URL 中提取文件名
      url: url
      }
    )

    fileList.value.forEach((file,index)=>{
      file.name = '附件' +(index+1)
    })
    fileList1.value.push(
      {
        uid: new Date().getTime(), // 生成唯一的 uid
      name: url.split('/').pop(), // 从 URL 中提取文件名
      url: url1
      }
    )

    fileList1.value.forEach((file,index)=>{
      file.name = '附件' +(index+1)
    })

    console.log(fileList1.value)
}

const getSampleChangeApi = async ()=>{
 const res = await  SampleInformationApi.getSampleChange({})
 console.log(res,'getSampleChangeApi')
}



const goBack = () => {
  router.back()
}
// 文件下载
const handlePreview = (file)=>{
  console.log(file,'file')
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg','pdf'];
  const fileExtension = file.url.split('.').pop().toLowerCase();
  if (imageExtensions.includes(fileExtension)) {
        // 如果是图片，在新窗口中打开
        window.open(file.url, '_blank');
    } else {
        // 不是图片，进行文件下载
        const a = document.createElement('a');
        const url = file.url;
        a.download = file.name;
        a.href = url;
        a.click();
    }
}

onMounted(()=>{
  getDetails()
  // getSampleChangeApi()

  if(route.query.id){
    route.meta.title = '编辑样品详细信息查询'
  }else {
    route.meta.title = '新增样品详细信息查询'
  }
})

onActivated(()=>{
  getDetails()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title {
    font-size: 16px;
    font-weight: bold;
  }

  .right-button {
    display: flex;
    gap: 10px;
  }
}

.mb-4 {
  margin-bottom: 1rem;
}

.text-lg {
  font-size: 1.125rem;
}

.font-bold {
  font-weight: bold;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
</style> 